package game.model;

import java.util.ArrayList;
import game.utils.Util;

import java.util.List;
import java.util.Stack;

public class Deck extends Stack<Card> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3582364664223201620L;
	private boolean faceUp;
	private int counter = 0;

	public Deck(boolean u) {
		faceUp = u;
		if (!faceUp)
			createFullDeck();
	}

	/**
	 * Do two cards have the same color?
	 * @return int, 0 if the color of the cards are the same && the value of the cards are the same,
	 *  1 if the value of the card is great than the card passed, else -1.
	 */
	public Card pop() {
		Card c = (Card) (super.pop());
		counter--;
		//System.out.println("Pop: " + c.getColor() + " " + c.getValue());
		return c;
	}

	public Card peek() {
		Card c = (Card) (super.peek());
		if (faceUp)
			return c;
		else
			return c;

	}
    
	public Card push(Card c) {
		super.push(c);
		counter++;
		//System.out.println("Push: " + c.getColor() + " " + c.getValue());
		return peek();

	}

	private void createFullDeck() {
		List<Card> newDeck = new ArrayList<Card>();
		for (int x = 0; x < 4; x++) {
			for (int y = 0; y < 25; y++) {
				if (y == 0)
					newDeck.add(new Card(Util.colors[x], 0));
				else
					newDeck.add(new Card(Util.colors[x], (int) ((y / 2.) + .5)));
			}
		}
		for (int x = 0; x < 2; x++) {
			for (int y = 0; y < 4; y++) {
				if (x == 0)
					newDeck.add(new Card(Util.colors[4], 0));
				else
					newDeck.add(new Card(Util.colors[4], 1));
			}
		}

		while (!newDeck.isEmpty()) {
			int rand = (int) (Math.random() * newDeck.size());
			this.push((Card) (newDeck.get(rand)));
			newDeck.remove(rand);
		}
	}
	
	public Card refillDeck(Deck d) {
		if(!faceUp && this.getCounter() == 0){
			Card top = d.pop();
			List<Card> newDeck = new ArrayList<Card>();
			newDeck.addAll(d);
			while (!newDeck.isEmpty()) {
				int rand = (int) (Math.random() * newDeck.size());
				this.push(newDeck.get(rand));
			}
			return top;
		}
		else
			return null;
	}
	
	/**
	 * @return the counter
	 */
	public int getCounter() {
		return counter;
	}
}
